import { defineStore } from 'pinia';
import { useMenuApi } from '@/api/menu-api';
import { AppComstants, RStatus } from '@/common/comstants';
import { appLocalStorage } from '@/utils/storage-util';
import { updateRoute } from '@/utils/router-update-util';
import { useTabStore } from './tab-store';

export const useMenuStore = defineStore('system', {
  state: () => {
    return {
      menuList: [],
      routerUpdate: false,
    };
  },
  actions: {
    /** 路由转换 */
    async fetchRoutes(router) {
      const res = await useMenuApi().getMenuWithPerms();

      if (res.status === RStatus.SUCCESS) {
        appLocalStorage.setItem(AppComstants.MENUS, res.data);
        this.menuList = updateRoute(res.data);
        this.routerUpdate = true;

        this.menuList.forEach((route) => {
          router.addRoute('layout', route);
        });
      }

      useTabStore().closeAllTabs();
      router.push(useTabStore().activeTab);
    },
  },
});
